<template>
  <div class="container">
    <div class="app-container">
      <ImportExcel v-model="showDialog" @refresh="getEmployeeList" />
      <el-dialog :visible.sync="showRoleDialog" title="分配角色">
        <!-- 弹层内容 -->
        <!-- checkbox -->
        <el-checkbox-group v-model="roleIds">
          <!-- 放置n个的checkbox  要执行checkbox的存储值 item.id-->
          <el-checkbox
            v-for="item in roleList"
            :key="item.id"
            :label="item.id"
          >{{ item.name }}</el-checkbox>

        </el-checkbox-group>
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button type="primary" size="mini" @click="btnRoleOK">确定</el-button>

            <el-button size="mini" @click="showRoleDialog = false">取消</el-button>

          </el-col>

        </el-row>

      </el-dialog>

      <div class="left">
        <el-input v-model="keyword" style="margin-bottom:10px" type="text" prefix-icon="el-icon-search" size="small" placeholder="输入员工姓名全员搜索" @input="handleInput" />
        <!-- 树形组件 -->
        <el-tree
          ref="tree"
          node-key="id"
          :data="depts"
          :props="{label: 'name', }"
          default-expand-all
          :expand-on-click-node="true"
          highlight-current
          @current-change="handleCurerentChange"
        />
      </div>

      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button v-permission="'add_employee'" size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>

          <el-button v-permission="'excel_import'" size="mini" @click="showDialog=true">excel导入</el-button>

          <el-button v-permission="'excel_export'" :loading="loading" size="mini" @click="handleExport">excel导出</el-button>

        </el-row>

        <!-- 表格组件 -->
        <el-table :data="rows">
          <el-table-column align="center" label="头像">
            <template #default="{row}">
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" />
              <span v-else class="hhh">{{ row.username.slice(2,3) }}</span>
            </template>

          </el-table-column>
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="手机号" sortable prop="mobile" />
          <el-table-column label="工号" sortable prop="workNumber" />
          <el-table-column label="聘用形式">
            <template #default="{row}">
              <span>{{ row.formOfEmployment=== 1 ? '正式':'非正式' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry" />
          <el-table-column label="操作" width="280px">
            <template #default="{row}">
              <el-button size="mini" type="text" @click="$router.push('/employee/detail/'+row.id)">查看</el-button>

              <el-button size="mini" type="text" @click="btnRole(row.id)">角色</el-button>

              <el-button size="mini" type="text">删除</el-button>

            </template>

          </el-table-column>

        </el-table>

        <!-- 分页 -->
        <el-row style="height: 60px" align="middle" type="flex" justify="end">
          <el-pagination
            layout="total,prev, pager, next"
            :total="total"
            :current-page="page"
            @current-change="handlePageChange"
          />
        </el-row>

      </div>

    </div>

  </div>

</template>

<script>
import { getDepartments } from '@/api/department'
import { transList2TreeData } from '@/utils'
import { getEmployeeList, getFileData, getEnableRoleList, getEmployeeDetail, assignRole } from '@/api/employee'
import FileSaver from 'file-saver'
import ImportExcel from './components/import-excel.vue'
export default {
  name: 'Employee',
  components: {
    ImportExcel
  },
  data() {
    return {
      depts: [],
      loading: false,
      showDialog: false,
      selectId: null,
      total: 0,
      rows: [],
      page: 1, // 当前页码
      keyword: '',
      // data中的数据如非必要不要写在这里
      // timer: null// 不需要在页面中展示定时器

      // data中为什么要提供数据？？？？什么数据一定要在data中提供？什么数据可以不提供？
      // 生命周期vue组件实例创建到销毁的全过程=>创建挂载更新销毁
      // 创建=>create处理数据（将data中的数据变成响应式数据）
      // 挂载=>mount
      // 更新=>update
      // 销毁=>destroy
      // 什么数据一定要在data中提供？===>>>这个数据需要在页面中展示且需要响应式效果一旦提供在data中会随着create
      // @State不一定不能滥用
      showRoleDialog: false, // 用来控制角色弹层的显示
      roleList: [], // 接收角色列表
      roleIds: [], // 用来双向绑定数据的
      currentId: null // 用来存储当前点击的角色按钮的id

    }
  },
  created() {
    this.getDepts()
  },

  methods: {
    // 点击角色按钮弹出层
    async btnRoleOK() {
      // console.log(this.roleIds)
      // console.log(this.currentId)
      await assignRole({
        id: this.currentId,
        roleIds: this.roleIds
      })

      this.$message.success('分配成功')
      this.showRoleDialog = false
      // 重新获取员工列表
      // this.getEmployeeList()
    },

    // 点击角色按钮弹出层
    async btnRole(id) {
      this.roleList = await getEnableRoleList()

      const { roleIds } = await getEmployeeDetail(id)
      this.roleIds = roleIds
      // console.log(roleIds)
      this.currentId = id
      // console.log(roleList)
      // 1.显示弹层
      this.showRoleDialog = true
    },
    async handleExport() {
      try {
        this.loading = true
        // 1．请求后端获取文件数据(封装接口时需要添加类型blob拦截器中不能剥离数据）
        const res = await getFileData()
        // this.loading = false
        // console.log(res)
        // 2.将文件数据下载下来成为一个文件（file-saver下包导包调包）
        FileSaver.saveAs(res, '员工数据.xlsx')
      } catch {
        // this.loading = false
        this.$message.error('导出失败')
      } finally {
        this.loading = false // 无论成功失败都要关闭loading
      }
    },
    handleInput() {
      // 防抖
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        // 用户输入时重置页码
        this.page = 1
        // 获取部门员工列表
        this.getEmployeeList()
      }, 500)
    },
    handlePageChange(val) {
      // val是当前点击页码
      // 更新当前页码
      this.page = val
      // 获取部门员工列表
      this.getEmployeeList()
    },
    async getEmployeeList() {
      const { total, rows } = await getEmployeeList({
        page: this.page,
        pagesize: 5,
        departmentId: this.selectId,
        keyword: this.keyword
      })
      // console.log(total, rows)
      this.total = total
      this.rows = rows
    },
    // 获取选中的节点
    handleCurerentChange(obj) {
      console.log(obj)
      // 记录id将来配合右侧进行数据展示
      this.selectId = obj.id
      // 重置页码
      this.page = 1

      // 获取选中部门员工列表
      this.getEmployeeList()
    },
    async getDepts() {
      const res = await getDepartments()
      // console.log(res)
      this.depts = transList2TreeData(res, 0) // 理好的数据赋值给depts然后tree组件就立即渲染出来了（等会出来的）
      // 一进入页面用户不选择部门时也需要默认获取传智教育的所有员工进行展示
      // 一旦获取数据立即将传智的id存下来
      this.selectId = this.depts[0].id
      // 等tree渲染完成后才能高亮
      this.$nextTick(() => {
        this.$refs.tree.setCurrentKey(this.selectId)
      })
      // 获取传智旗下员工列表
      this.getEmployeeList()
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }
}
.hhh{
  display: inline-block;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #8df;

  text-align: center;
  line-height: 40px;
  color: #fff;
  font-size: 20px;
}

</style>
